package com.bytech.article.biz.controller.article;

import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.annotation.Resource;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bytech.article.biz.service.articleTag.ArticleTagService;
import com.bytech.article.biz.service.tagToArticle.TagToArticleService;
import com.bytech.common.annotation.UserAgent;
import com.bytech.common.biz.entity.article.Article;
import com.bytech.common.biz.entity.article.ArticleQuery;

import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import com.bytech.article.biz.service.article.ArticleService;
import com.bytech.common.biz.controller.base.BasicController;
import com.bytech.common.biz.entity.article.ArticleDto;
import com.bytech.common.biz.entity.base.BaseResult;
import com.bytech.common.biz.entity.blogUser.BlogUserAgent;
import com.bytech.common.biz.entity.tagToArticle.TagToArticle;
import com.bytech.common.biz.entity.timeline.TimeLineYear;
import com.bytech.common.biz.enums.article.ArticleStatusEnum;
import com.bytech.common.utils.ApplicationBeanUtils;
import com.bytech.common.utils.StringUtils;
import com.google.common.collect.Lists;

/**
 * @Author Zhao
 * @Create 2021-07-26
 */
@RestController
@RequestMapping("/article")
public class ArticleController extends BasicController {

    @Resource
    private ArticleService articleService;
    @Resource
    private TagToArticleService tagToArticleService;
    @Resource
    private ArticleTagService articleTagService;

    @GetMapping("/{articleId}")
    public BaseResult<ArticleDto> getArticleDto(@PathVariable("articleId") String articleId, @UserAgent BlogUserAgent userAgent) {
        return BaseResult.<ArticleDto>success().data(articleService.getArticleDtoByIdAndViewer(articleId, userAgent.getId())).build();
    }

    /**
     * 获取当前博客的文章总数
     */
    @GetMapping("/articleCount")
    public BaseResult<Integer> getArticleCount() {
        return BaseResult.<Integer>success().data(articleService.getArticleCount()).build();
    }

    @GetMapping("/getArticleById")
    public BaseResult<ArticleDto> getArticleDto(@RequestParam("articleId") String articleId) {
        Article article = articleService.getById(articleId);
        ArticleDto articleDto = ApplicationBeanUtils.copyProperties(article, ArticleDto.class);
        LambdaQueryWrapper<TagToArticle> ttaQuery = new LambdaQueryWrapper<>();
        ttaQuery.eq(TagToArticle::getArticleId, articleId);
        List<TagToArticle> ttaList = tagToArticleService.list(ttaQuery);
        Optional.of(ttaList).ifPresent(e -> {
            List<Long> tagIds = e.stream().map(TagToArticle::getTagId).collect(Collectors.toList());
            articleDto.setTagIds(tagIds);
            articleDto.setTags(Lists.newArrayList(articleTagService.listByIds(tagIds)));
        });
        return BaseResult.<ArticleDto>success().data(articleDto).build();
    }

    @GetMapping("/getArticleByIds")
    public List<Article> getArticleDto(@RequestParam("articleIds") Collection<String> articleIds) {
        if (CollectionUtils.isEmpty(articleIds)) {
            return Lists.newArrayList();
        }
        return Lists.newArrayList(articleService.listByIds(articleIds));
    }

    @PostMapping("/save/")
    public BaseResult<Article> doSaveArticle(@RequestBody ArticleDto article) {
        if (StringUtils.isBlank(article.getCreator())) {
            return BaseResult.<Article>error("请先登录").build();
        }
        return articleService.saveArticle(article);
    }

    @PostMapping("/pageArticleByQuery")
    public BaseResult<Page<ArticleDto>> pageArticleByQuery(@RequestBody ArticleQuery<Article> articleQuery) {
        return BaseResult.<Page<ArticleDto>>success().data(articleService.pageArticleByQuery(articleQuery)).build();
    }

    @GetMapping("/pageUsableByQuery")
    public BaseResult<Page<ArticleDto>> pageUsableByQuery(ArticleQuery<Article> articleQuery) {
        articleQuery.setSize(5L);
        articleQuery.setStatus(ArticleStatusEnum.PUBLISHED.getValue());
        return pageArticleByQuery(articleQuery);
    }

    /**
     * 逻辑删除
     */
    @PostMapping("/delete")
    public BaseResult<String> deleteArticleById(@RequestParam String id) {
        Article article = articleService.getById(id);
        if (article == null) {
            return BaseResult.<String>error("文章不存在！").data(null).build();
        }
        article.setStatus(ArticleStatusEnum.DELETED.getValue());
        articleService.updateById(article);
        return BaseResult.<String>success("删除成功！").data(null).build();
    }

    /**
     * 物理删除
     */
    @PostMapping("/physicalDelete")
    public BaseResult<String> physicalDeleteArticleById(@RequestParam String id) {
        articleService.removeById(id);
        return BaseResult.<String>success("删除成功！").data(null).build();
    }

    @PostMapping("/toggleThumb")
    public BaseResult<Integer> doToggleThumb(String articleId, @UserAgent BlogUserAgent userAgent) {
        return articleService.toggleThumb(articleId, userAgent.getId());
    }

    @GetMapping("/timeline")
    public List<TimeLineYear> getArticleTimeLine() {
        return articleService.buildTimeLine();
    }
}
